<template>
  <div class="scan-code">
    <img src="@/assets/img/scan.svg" width="24" alt="" @click="ready" />
    <div class="scan-code-content" :style="{ visibility: isReady ? 'visible' : 'hidden' }" @click="destroy">
      <div id="barcode">
        <div style="height: 100%"></div>
        <p class="item" v-if="!isReady">载入中...</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "scanCode",
  data() {
    return {
      scan: null,
      isReady: false,
    };
  },
  beforeDestroy() {
    this.destroy();
  },
  methods: {
    ready() {
      if (this.isReady) {
        return;
      }
      this.isReady = true;
      if (window.plus) {
        this.init();
      } else {
        document.addEventListener("plusready", this.init, false);
      }
    },
    init() {
      this.startRecognize();
      let timer = setTimeout(() => {
        this.startScan();
        clearTimeout(timer);
        timer = null;
      }, 2000);
    },
    destroy() {
      document.removeEventListener("plusready", this.init, false);
      this.cancelScan();
      this.closeScan();
      this.isReady = false;
    },
    //创建扫描控件
    startRecognize() {
      //filter 扫描类型
      const filter = [
        plus.barcode.CODE128,
        plus.barcode.EAN13,
        plus.barcode.EAN8,
        plus.barcode.QR,
      ];
      this.scan = new plus.barcode.Barcode("barcode", filter);
      this.scan.onmarked = this.onmarked;
    },
    onmarked(type, result) {
      switch (type) {
        case plus.barcode.QR:
          type = "QR";
          break;
        case plus.barcode.EAN13:
          type = "EAN13";
          break;
        case plus.barcode.EAN8:
          type = "EAN8";
          break;
        case plus.barcode.CODE128:
          type = "EAN8";
          break;
        default:
          type = "其它" + type;
          break;
      }
      this.$emit("scan", {
        type: type,
        result: result,
      });
      this.destroy();
    },
    // 关闭控件a
    closeScan() {
      this.scan?.close();
    },
    startScan() {
      this.scan?.start();
    },
    // 关闭扫描
    cancelScan() {
      this.scan?.cancel();
    },
  },
};
</script>

<style lang="less" scoped>
.scan-code {
  &-content {
    width: 100%;
    height: 100vh;
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    text-align: center;
    color: #fff;
    background: #3535358f;
    z-index: 9999;
    display: flex;
    align-items: center;
    justify-content: center;
    #barcode {
      margin: 0 auto;
      display: flex;
      flex-direction: column;
      gap: 10px;
      align-items: center;
      width: 300px;
      height: 300px;
    }
  }
  .item {
    font-weight: 400;
    font-size: 14px;
    line-height: 20px;
    letter-spacing: 0px;
    text-align: center;
    color: #fff;
  }
}
</style>
